﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SinBiota.Model.Business.AuthenticationServices.Interfaces;
using SinBiota.Model.Entities;
using StructureMap;

namespace Sinbiota.Web.ActionFilters
{

    public class AdminPermissionAttribute : AuthorizeAttribute
    {
        private readonly IPermissionServices _permissionServices;
        public AdminPermissionAttribute()
        {
            if (_permissionServices == null)
                _permissionServices = ObjectFactory.GetInstance<IPermissionServices>();
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            return httpContext.User.Identity.IsAuthenticated && _permissionServices.IsAdmin(httpContext.User.Identity.Name);
        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if (!(filterContext.Result is HttpUnauthorizedResult)) return;

            filterContext.Result = filterContext.HttpContext.Request.IsAjaxRequest()
                                       ? (ActionResult)new JavaScriptResult() { Script = "alert('unauthorized request');" }
                                       : new ViewResult {ViewName = "NonAuthorized"};
        }

    }
}